<template v-if="text">
  <div class="u-code-json">
    <el-popover placement="right" trigger="click" width="auto">
      <template #reference>
        <span class="text">{{ text }}</span>
      </template>
      <div class="main">
        <div class="op">
          <el-button type="success" size="small" @click="copy(text)">copy</el-button>
        </div>
        <el-scrollbar class="scrollbar" :max-height="maxHeight">
          <pre><code>{{ text }}</code></pre>
        </el-scrollbar>
      </div>
    </el-popover>
  </div>
</template>

<script lang="ts" name="u-code-json" setup>
import { ElMessage } from 'element-plus';
import { isObject, isString } from 'undraw-ui'
import { computed } from 'vue'

interface Props {
  modelValue: string
  height: number | string
  maxHeight: number | string
}

const props = withDefaults(defineProps<Props>(), {
  height: '100%',
  maxHeight: 300
})

// 文本
const text = computed(() => {
  const v = props.modelValue

  if (isString(v)) {
    return v
  } else if (isObject(v)) {
    return JSON.stringify(v, null, 4)
  } else {
    return ''
  }
})

function copy(val: any) {
  let copy = useClipboard()
  copy(val).then(() => {
    console.log('test')
    ElMessage.success('复制成功!')
  }).catch(() => {
    ElMessage.warning('复制失败!')
  })
}


function useClipboard() {
  return (text: any) => new Promise((resolve, reject) => {
    // 使用navigator对象对其他现代浏览器支持的API
    navigator.clipboard.writeText(text).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}
</script>

<style lang="scss" scoped>
.u-code-json {
  background-color: var(--el-fill-color-lighter);
  border-radius: 6px;

  .text {
    display: block;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    cursor: pointer;

    &:hover {
      color: var(--color-primary);
    }
  }
}
.main {
  max-width: 500px;
  .op {
    display: flex;
    justify-content: end;
  }

  .scrollbar {
    code {
      display: block;
      font-size: 14px;
      white-space: pre-wrap;
    }
  }
}
</style>
